/**
 * 事件埋点方法的封装
 */

import { isAliyunDomain } from 'utils/tenant';
import {
  track as aplusTrack,
  sendPV as aplusSendPV,
  sendPerf,
  Perf,
  register,
} from '@alife/yunxiao-common';
import AESPluginEvent from '@ali/aes-tracker-plugin-event';
import { switchPage as aemSwitchPage, sendPV as aemSendPV } from '@ali/aes-tracker-plugin-pv';

const track = (...args) => {
  if (!args[0]) {
    return false;
  }

  // 非正式环境、非阿里云环境不打点
  const { env } = window.FORCE;
  if (env !== 'PRODUCTION' && isAliyunDomain) {
    return false;
  }

  aplusTrack(...args);

  // aem事件埋点 https://yuque.antfin-inc.com/aes/help/xyf16m
  const { action, page, ...others } = args[0];
  if (action) {
    // 为了方便在 aem 操作流视图（仅展示action）查看完整用户操作，将 enter page action和page拼一起
    let event = action;
    if (action === 'enter page') {
      event = `${action}_${page}`;
    }

    AESPluginEvent(event, {
      // 事件类型
      et: 'CLK', // or 'EXP'

      ...others,
    });
  }
};

// 页面pv埋点，在进入页面时埋
const enterPage = (
  page = '',
  { sendPV: sendPVParm, sendPerf: sendPerfParm, pathname, ...others } = {
    sendPV: true,
    sendPerf: true,
  },
) => {
  const needSendPV = sendPVParm === undefined ? true : sendPVParm;
  const needSendPerf = sendPerfParm === undefined ? true : sendPerfParm;

  // 发送SPM
  if (needSendPV) {
    sendPV(window.FORCE.assetsName, pathname || window.location.pathname);
  }

  // 发送黄金令剑
  track({
    action: 'enter page',
    page,
    ...others,
  });

  // 发送aem pv埋点
  // https://yuque.antfin-inc.com/aes/help/zundfg#kZNQj
  aemSwitchPage({
    page_id: page, // 用于标示页面的唯一ID，默认为去协议、QueryString、Hash的URL
  });
  aemSendPV();

  // 发送性能黄金令剑
  if (needSendPerf) {
    sendPerf({ page, ...others });
  }
};

// 页面pv埋点，在进入弹层或弹窗时埋
const enterModal = enterPage;

// 发送SPM
const sendPV = (assetsName, path) => {
  const spmA = 'a2cl9';
  const globalParams = {
    orgId: window.config && window.config.orgId,
    mp_lib: 'aliyun_codeup',
    userId: window.FORCE && window.FORCE.user && window.FORCE.user.id,
    userRole: window.FORCE && window.FORCE.organization && window.FORCE.organization.user_role,
  };

  // assetsName是organization和projectSettings时，是前端接管的路由，拼上pathname作为pageId
  let pageId;
  switch (assetsName) {
    case 'organization':
      pageId = `${assetsName}${path}`;
      break;
    case 'projectSettings':
      pageId = `${assetsName}/${path.split('/')[path.split('/').length - 1]}`;
      break;
    default:
      pageId = assetsName;
      break;
  }

  aplusSendPV(spmA, `codeup_devops2020_goldlog_${pageId}`, globalParams);
};

export { track, enterPage, enterModal, sendPV, Perf, register };
export default track;
